#include "connection.h"

Connection::Connection(QObject *parent) :
    QObject(parent)
{
    _socket = new QTcpSocket(this);
}

Connection::Connection(const Connection &connection) :
    QObject()
{
    _socket = connection.socket();
}

bool Connection::connect(const QString address, const quint16 port)
{
    socket()->connectToHost(address,port);
    if(socket()->waitForConnected())
    {
        if(socket()->waitForReadyRead())
        {
            emit connected();
            return true;
        }
    }
    return false;
}

void Connection::disconnect()
{
    if(socket()->isOpen())
    {
        emit disconnecting();
        socket()->disconnectFromHost();
        socket()->waitForDisconnected();
    }
}

void Connection::send(const QString bytes)
{
    socket()->write(bytes.toUtf8());
    emit lineSended(bytes.simplified());
}

void Connection::send(const QByteArray bytes)
{
    socket()->write(bytes);
    emit dataSended(bytes);
}

const QByteArray Connection::receive(const int lenght)
{
    QByteArray array = QByteArray();
    int _count = 0;
    while(_count < lenght)
    {
        socket()->waitForReadyRead(10);
        array.append(socket()->read(lenght - _count));
        _count = array.size();
        emit dataReceiving((qreal)_count / lenght);
    }
    emit dataReceiving((qreal)1);
    emit dataReceived(array);
    return array;
}

const QString Connection::receiveLine()
{
    QString tmp;
    while(!socket()->canReadLine())
    {
        tmp += QString::fromUtf8(socket()->readAll());
        socket()->waitForReadyRead();
    }
    tmp +=  QString::fromUtf8(socket()->readLine());
    emit lineReceived(tmp.simplified());
    return tmp;
}

bool Connection::isConnected() const
{
    return (socket()->state() == QAbstractSocket::ConnectedState);
}

QTcpSocket *Connection::socket() const
{
    return _socket;
}
